package com.hitemole.network;

import java.io.IOException;
import java.util.ArrayList;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Vector2;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.esotericsoftware.kryonet.Server;
import com.hitemole.network.Network.ClientInfo;
import com.hitemole.network.Network.GameMessage;

public class ServerGame {

	public static final ServerGame serverGame = new ServerGame();
	private Server server, broadcastServer;
	private ArrayList<Vector2> userInput = new ArrayList<Vector2>();
	private static final String DEBUG_LOG = serverGame.getClass().getName();
	private ClientInfo client;

	private ServerGame() {

	}

	public void createNewServer() throws IOException {
		Gdx.app.debug(DEBUG_LOG, "Start Game Server");
		System.out.println("Start Game Server");
		if (server == null)
			server = new Server();
		broadcastServer = new Server();
		Network.register(server);
		Network.register(broadcastServer);

		server.addListener(new Listener() {
			@Override
			public void connected(Connection arg0) {
				// TODO Auto-generated method stub
				System.out.println("client connected at: "
						+ arg0.getRemoteAddressTCP().getAddress());
				super.connected(arg0);
			}

			@Override
			public void received(Connection arg0, Object object) {

				if (object instanceof ClientInfo) {
					ClientInfo clientInfo = (ClientInfo)object;
					client=clientInfo;
					return;
				}

				// TODO Auto-generated method stub
				if (object instanceof GameMessage) {
					GameMessage gameMessage = (GameMessage) object;
					userInput.add(new Vector2(gameMessage.mouseClick));
				}
				super.received(arg0, object);
			}

			@Override
			public void disconnected(Connection arg0) {
				// TODO Auto-generated method stub
				System.out.println("client disconnected");
				server.stop();
				broadcastServer.stop();
				super.disconnected(arg0);
			}
		});
		server.bind(Network.tcpPort);
		broadcastServer.bind(0, Network.udpPort);
		server.start();
		broadcastServer.start();
	}
	
	

	public void sendToClient(GameMessage gm) {
		Gdx.app.debug(DEBUG_LOG, "Broadcast to Client");
		if (server != null && isClientConnected())
			server.sendToAllTCP(gm);
	}

	public boolean isClientConnected() {
		if (server != null)
			return server.getConnections().length > 0 ? true : false;
		return false;
	}

	public ArrayList<Vector2> getUserInput() {
		return userInput;
	}

	public void stopServer() {
		System.out.println("Stopping Server");
		server.stop();
		broadcastServer.stop();
	}

	public void setUserInput(ArrayList<Vector2> userInput) {
		this.userInput = userInput;
	}

	public ClientInfo getClient() {
		return client;
	}

	public void setClient(ClientInfo client) {
		this.client = client;
	}

}
